package num166;

import java.util.HashMap;
import java.util.Map;

/**
 * 166. 分数到小数
 * 题目：https://leetcode-cn.com/problems/fraction-to-recurring-decimal
 * 三叶姐题解: https://leetcode-cn.com/problems/fraction-to-recurring-decimal/solution/gong-shui-san-xie-mo-ni-shu-shi-ji-suan-kq8c4/
 * 三叶姐
 */
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        long a = numerator, b = denominator;

        if (a % b == 0) {
            return String.valueOf(a / b);
        }

        StringBuilder sb = new StringBuilder();

        if (a * b < 0) {
            sb.append("-");
        }

        a = Math.abs(a);
        b = Math.abs(b);

        sb.append(a / b + ".");

        a %= b;
        HashMap<Long, Integer> map = new HashMap<>();

        while (a != 0) {
            map.put(a, sb.length());
            a *= 10;
            sb.append(a / b);
            a %= b;
            if (map.containsKey(a)) {
                int u = map.get(a);
                return String.format("%s(%s)", sb.substring(0, u), sb.substring(u));
            }
        }
        return sb.toString();
    }
}
